<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 提示 -->
      <el-alert
        type="warning"
        show-icon=""
        title="注意：只允许为第三级分类设置相关参数！"
      ></el-alert>
      <!-- 分类选择器 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span
          ><el-cascader
            :options="cateList"
            :props="cascaderProps"
            v-model="selectedCate"
            @change="cateChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="selectedTab" @tab-click="tabChange">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="showDialog"
            >添加参数</el-button
          >
          <!-- 参数列表 -->
          <el-table :data="attributesList" border stripe>
            <!-- 扩展列 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleTagClose(scope.row, index)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <!-- 数据列 -->
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="getAttrById(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeAttrById(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="showDialog"
            >添加属性</el-button
          >
          <!-- 属性列表 -->
          <el-table :data="attributesList" border stripe>
             <!-- 扩展列 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleTagClose(scope.row, index)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <!-- 数据列 -->
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="getAttrById(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeAttrById(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加/编辑参数对话框 -->
    <el-dialog
      :title="dialogProps.title"
      :visible.sync="dialogProps.visible"
      width="50%"
      :close-on-click-modal="false"
      :show-close="false"
      @closed="dialogClose"
    >
      <el-form ref="Form" :model="Form" :rules="formRules">
        <el-form-item
          :label="dialogProps.label"
          label-width="80px"
          prop="attr_name"
        >
          <el-input v-model="Form.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogProps.visible = false">取 消</el-button>
        <el-button type="primary" @click="dialogClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [],
      cascaderProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        expandTrigger: "hover",
      },
      selectedCate: [],
      selectedTab: "many",
      attributesList: [],
      // 对话框配置
      dialogProps: {
        title: "",
        label: "",
        visible: false,
        // 是否为编辑参数模式
        edit: false,
      },
      // 对话框表单对象
      Form: {
        attr_id: 0,
        attr_name: "",
      },
      // 表单验证规则
      formRules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 获取分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cateList = res.data;

      this.$message.success(res.meta.msg);
    },
    // 分类切换监听
    cateChange() {
      if (this.selectedCate.length !== 3) {
        this.selectedCate = [];
        this.attributesList = [];
        return this.$message.error("只允许为第三级分类设置相关参数！");
      }
      this.getAttributeList();
    },
    // 标签切换监听
    tabChange() {
      //   console.log(this.selectedTab);
      this.getAttributeList();
    },
    // 获取动态参数/静态属性
    async getAttributeList() {
      if(this.cateId){
         const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.selectedTab } }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      // 预处理数据
      res.data.forEach((item) => {
        // 数据字符串转换为数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        // 新增两个属性，用于添加新tag
        (item.inputVisible = false), (item.inputValue = "");
      });

      this.attributesList = res.data;
      this.$message.success(res.meta.msg);
      }
     
    },
    // 打开添加参数对话框
    showDialog() {
      if (this.selectedTab == "many") {
        this.dialogProps.title = "添加动态参数";
        this.dialogProps.label = "参数名称";
      } else {
        this.dialogProps.title = "添加静态属性";
        this.dialogProps.label = "属性名称";
      }
      this.dialogProps.edit = false;
      this.dialogProps.visible = true;
    },
    // 对话框关闭
    dialogClose() {
      this.$refs.Form.resetFields();
    },
    // 对话框“确认”按钮事件
    dialogClick() {
      if (this.dialogProps.edit) this.editAttribute();
      else this.addAttribute();
    },
    // 提交新参数
    addAttribute() {
      this.$refs.Form.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          { attr_name: this.Form.attr_name, attr_sel: this.selectedTab }
        );
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);

        this.dialogProps.edit = false;
        this.dialogProps.visible = false;
        this.getAttributeList();
        this.$message.success(res.meta.msg);
      });
    },
    // 根据id获取参数信息
    async getAttrById(id) {
      this.dialogProps.attr_id = id;

      if (this.selectedTab == "many") {
        this.dialogProps.title = "编辑动态参数";
        this.dialogProps.label = "参数名称";
      } else {
        this.dialogProps.title = "编辑静态属性";
        this.dialogProps.label = "属性名称";
      }
      this.dialogProps.edit = true;
      this.dialogProps.visible = true;

      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        { params: { sel: this.selectedTab } }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.Form = res.data;
      // console.log(this.Form);
      this.$message.success(res.meta.msg);
    },
    // 提交编辑的参数信息
    editAttribute() {
      this.$refs.Form.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.Form.attr_id}`,
          { attr_name: this.Form.attr_name, attr_sel: this.selectedTab }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.dialogProps.edit = false;
        this.dialogProps.visible = false;
        this.getAttributeList();
        this.$message.success(res.meta.msg);
      });
    },
    // 根据id移除参数
    removeAttrById(id) {
      // console.log(id)
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${id}`
          );
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.$message.success(res.meta.msg);
          this.getAttributeList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 当输入框失去焦点或按下Enter时触发
    handleInputConfirm(row) {
      // 如果输入合法则发起请求
      if (row.inputValue.trim().length !== 0) {
        row.attr_vals.push(row.inputValue.trim());
        this.commitAttrValsChange(row);
      }
      // 重置
      row.inputValue = "";
      row.inputVisible = false;
    },
    // 显示输入框并聚焦
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleTagClose(row, index) {
      // 移除tag对应的元素
      row.attr_vals.splice(index, 1);
      this.commitAttrValsChange(row);
    },
    // 提交修改/删除的参数值
    async commitAttrValsChange(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.selectedTab,
          attr_vals: row.attr_vals.join(","),
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
    },
  },
  created() {
    this.getCateList();
  },
  computed: {
    // “添加”按钮是否禁用
    isBtnDisable() {
      return this.selectedCate.length !== 3 ? true : false;
    },
    // 当前选中分类的id
    cateId() {
      if (this.selectedCate.length === 3)
        return this.selectedCate[this.selectedCate.length - 1];
      return null;
    },
  },
};
</script>
<style lang='less' scoped>
.el-alert {
  margin-bottom: 20px;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 170px;
}
</style>